package com.baibei.sdk;

import android.util.Log;

import com.github.raee.runit.AndroidRUnit4ClassRunner;

import junit.framework.Assert;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.observers.DefaultObserver;

/**
 * 测试回调
 * Created by ChenRui on 2017/4/28 0028 14:25.
 */
public class TestDefaultObserver<T> extends DefaultObserver<T> {

    private String methodName;
    private static final String TAG = "rae-api";

    public TestDefaultObserver(String methodName) {
        this.methodName = methodName;
    }

    @Override
    public void onNext(T t) {

        if (t == null) {
            Log.w(TAG, methodName + "：返回结果为空！");
            Assert.fail(methodName + "：返回结果为空！");
            return;
        }


        Class<?> aClass = t.getClass();

        if (aClass == String.class) {
            Log.i(TAG, t.toString());
            return;
        }

        if (aClass == List.class || aClass == ArrayList.class) {
            // 打印数组
            printf(aClass.getName(), (Iterable<?>) t);
            return;
        }

        Class<?>[] interfaces = aClass.getInterfaces();
        if (interfaces != null) {
            for (Class<?> anInterface : interfaces) {
                if (anInterface == Iterable.class) {
                    // 打印数组
                    printf(anInterface.getName(), (Iterable<?>) t);
                    return;
                }
            }
        }


        // 打印对象
        printObject(t);
    }

    @Override
    public void onError(Throwable e) {
        Assert.fail(e.getMessage());
        AndroidRUnit4ClassRunner.finish(methodName);
    }

    @Override
    public void onComplete() {
        Log.d(TAG, methodName + "：测试完成！");
        AndroidRUnit4ClassRunner.finish(methodName);
    }

    /**
     * 打印对象
     *
     * @param m
     */
    protected void printObject(Object m) {
        Class cls = m.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            if (name.equalsIgnoreCase("CREATOR")) continue;
            field.setAccessible(true);


            try {

                if (field.getType() == List.class) {
                    printf(name, (Iterable<?>) field.get(m));
                    continue;
                }

                Log.d(TAG, name + " = " + field.get(m));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }


    protected <F> void printf(String fieldName, Iterable<F> m) {
        if (m == null) {
            Log.w(TAG, fieldName + " =  empty");
            return;
        }
        for (F item : m) {
            Log.d(TAG, "---------------");
            printObject(item);
        }
    }
}
